import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../../common/styles/theme_manager.dart';
import '../../../core/repository/default_api.dart';
import '../../../services/device_sn_manager.dart';
import 'dart:developer' as developer;

/// 测量类型枚举
enum MeasureType {
  heartRate, // 心率
  bloodOxygen, // 血氧
  pressure, // 压力
  hrv, // 心率变异性
}

/// 测量记录模型
class MeasureRecord {
  final String? id;
  final int value;
  final String time;
  final String date;
  final String weekName;
  final String? unit;

  MeasureRecord({
    this.id,
    required this.value,
    required this.time,
    required this.date,
    required this.weekName,
    this.unit,
  });

  factory MeasureRecord.fromJson(Map<String, dynamic> json, MeasureType type) {
    int value = 0;
    String? unit;

    switch (type) {
      case MeasureType.heartRate:
        value = json['generalValue'] as int? ?? 0;
        unit = 'BPM';
        break;
      case MeasureType.bloodOxygen:
        value = json['generalValue'] as int? ?? 0;
        unit = '%';
        break;
      case MeasureType.pressure:
        value = json['generalValue'] as int? ?? 0;
        unit = '';
        break;
      case MeasureType.hrv:
        value = json['generalValue'] as int? ?? 0;
        unit = '毫秒';
        break;
    }

    return MeasureRecord(
      id: json['id']?.toString(),
      value: value,
      time: json['endHi'] as String? ?? '',
      date: json['dailyValue'] as String? ?? '',
      weekName: json['weekName'] as String? ?? '',
      unit: unit,
    );
  }
}

/// 手动测量记录页面
class ManualMeasureView extends StatefulWidget {
  const ManualMeasureView({super.key});

  @override
  State<ManualMeasureView> createState() => _ManualMeasureViewState();
}

class _ManualMeasureViewState extends State<ManualMeasureView> {
  late MeasureType measureType;
  final RxList<MeasureRecord> records = <MeasureRecord>[].obs;
  final RxBool isLoading = false.obs;

  @override
  void initState() {
    super.initState();
    // 从路由参数获取测量类型
    final args = Get.arguments as Map<String, dynamic>?;
    final typeStr = args?['type'] as String? ?? 'heartRate';
    measureType = MeasureType.values.firstWhere(
      (e) => e.name == typeStr,
      orElse: () => MeasureType.heartRate,
    );
    _fetchRecords();
  }

  /// 获取测量记录
  Future<void> _fetchRecords() async {
    try {
      isLoading.value = true;
      developer.log('📊 开始获取${_getTitle()}手动测量记录...', name: 'ManualMeasure');

      final deviceSnManager = Get.find<DeviceSnManager>();
      final deviceSn = deviceSnManager.getDeviceSn();
      final now = DateTime.now();
      final recordDate =
          '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';

      Map<String, dynamic>? response;

      switch (measureType) {
        case MeasureType.heartRate:
          response =
              await DefaultApi().queryHeartRateMeasureGet<Map<String, dynamic>>(
            deviceSn: deviceSn,
            recordDate: recordDate,
            type: '3',
            isShowErrMsg: false,
            isShowLoading: false,
          );
          break;
        case MeasureType.bloodOxygen:
          response =
              await DefaultApi().queryBloodOxygenInfoGet<Map<String, dynamic>>(
            deviceSn: deviceSn,
            recordDate: recordDate,
            type: '3',
            isShowErrMsg: false,
            isShowLoading: false,
          );
          break;
        case MeasureType.pressure:
          response =
              await DefaultApi().queryPressureInfoGet<Map<String, dynamic>>(
            deviceSn: deviceSn,
            recordDate: recordDate,
            type: '3',
            isShowErrMsg: false,
            isShowLoading: false,
          );
          break;
        case MeasureType.hrv:
          response = await DefaultApi().queryHrvInfoGet<Map<String, dynamic>>(
            deviceSn: deviceSn,
            recordDate: recordDate,
            type: '3',
            isShowErrMsg: false,
            isShowLoading: false,
          );
          break;
      }

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null && data is List) {
          final List<MeasureRecord> allRecords = [];

          for (var dayData in data) {
            final dailyValue = dayData['dailyValue'] as String? ?? '';
            final weekName = dayData['weekName'] as String? ?? '';
            final jsonObjectVOList = dayData['jsonObjectVOList'] as List?;

            if (jsonObjectVOList != null) {
              for (var item in jsonObjectVOList) {
                final record = MeasureRecord.fromJson(
                  {
                    ...item as Map<String, dynamic>,
                    'dailyValue': dailyValue,
                    'weekName': weekName,
                  },
                  measureType,
                );
                allRecords.add(record);
              }
            }
          }

          records.value = allRecords;
          developer.log('✅ 获取到 ${records.length} 条手动测量记录',
              name: 'ManualMeasure');
        }
      }
    } catch (e) {
      developer.log('❌ 获取手动测量记录失败: $e', name: 'ManualMeasure');
    } finally {
      isLoading.value = false;
    }
  }

  String _getTitle() {
    switch (measureType) {
      case MeasureType.heartRate:
        return '心率';
      case MeasureType.bloodOxygen:
        return '血氧';
      case MeasureType.pressure:
        return '压力';
      case MeasureType.hrv:
        return '心率变异性';
    }
  }

  IconData _getIcon() {
    switch (measureType) {
      case MeasureType.heartRate:
        return Icons.favorite_border;
      case MeasureType.bloodOxygen:
        return Icons.water_drop_outlined;
      case MeasureType.pressure:
        return Icons.psychology_outlined;
      case MeasureType.hrv:
        return Icons.show_chart;
    }
  }

  Color _getColor() {
    switch (measureType) {
      case MeasureType.heartRate:
        return const Color(0xFFFFD700);
      case MeasureType.bloodOxygen:
        return const Color(0xFF6CA6FF);
      case MeasureType.pressure:
        return const Color(0xFFED5C2F);
      case MeasureType.hrv:
        return const Color(0xFF00C08B);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Column(
          children: [
            _buildHeader(),
            Expanded(
              child: Obx(() {
                if (isLoading.value) {
                  return Center(
                    child: CircularProgressIndicator(
                      valueColor:
                          AlwaysStoppedAnimation<Color>(Colors.grey[400]!),
                    ),
                  );
                }

                if (records.isEmpty) {
                  return _buildEmptyState();
                }

                return ListView.builder(
                  padding: EdgeInsets.all(16.w),
                  itemCount: records.length,
                  itemBuilder: (context, index) {
                    final record = records[index];
                    return _buildRecordItem(record);
                  },
                );
              }),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topRight,
          end: Alignment.bottomRight,
          colors: ThemeManager.to.backgroundGradientColors,
          stops: const [0.1, 0.3, 0.7, 1.0],
        ),
      ),
      child: Row(
        children: [
          IconButton(
            onPressed: () => Get.back(),
            icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
          ),
          Expanded(
            child: Center(
              child: Text(
                _getTitle(),
                style: TextStyle(
                  fontSize: 18.sp,
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ),
          SizedBox(width: 48.w),
        ],
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            _getIcon(),
            size: 64.sp,
            color: Colors.grey[600],
          ),
          SizedBox(height: 16.h),
          Text(
            '暂无手动测量记录',
            style: TextStyle(
              fontSize: 16.sp,
              color: Colors.grey[400],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRecordItem(MeasureRecord record) {
    final color = _getColor();
    return GestureDetector(
      onTap: () {
        Get.toNamed(
          '/measure-detail',
          arguments: {
            'type': measureType.name,
            'recordId': record.id ?? '',
          },
        );
      },
      child: Container(
        margin: EdgeInsets.only(bottom: 12.h),
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: const Color.fromRGBO(3, 0, 3, 1),
          borderRadius: BorderRadius.circular(20.r),
          border: Border.all(
            color: const Color.fromRGBO(33, 33, 33, 1),
            width: 1,
          ),
        ),
        child: Row(
        children: [
          // 测量值
          Container(
            width: 80.w,
            height: 80.w,
            decoration: BoxDecoration(
              color: color.withValues(alpha: 0.2),
              shape: BoxShape.circle,
            ),
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    '${record.value}',
                    style: TextStyle(
                      fontSize: 28.sp,
                      fontWeight: FontWeight.bold,
                      color: color,
                    ),
                  ),
                  if (record.unit != null && record.unit!.isNotEmpty)
                    Text(
                      record.unit!,
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: color,
                      ),
                    ),
                ],
              ),
            ),
          ),
          SizedBox(width: 16.w),
          // 时间和日期
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '${record.date}，${record.weekName}',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.grey[400],
                  ),
                ),
                SizedBox(height: 4.h),
                Text(
                  record.time,
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
          ),
          Icon(
            Icons.chevron_right,
            color: Colors.grey[600],
            size: 24.sp,
          ),
        ],
      ),
    ),
    );
  }
}
